package com.ming.mallchat.common.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.mallchat.common.common.annotation.RedissonLock;
import com.ming.mallchat.common.common.domain.enums.YesOrNoEnum;
import com.ming.mallchat.common.common.event.ItemReceiveEvent;
import com.ming.mallchat.common.common.utils.AssertUtil;
import com.ming.mallchat.common.user.dao.UserBackPackDao;
import com.ming.mallchat.common.user.domain.enums.IdempotentEnum;
import com.ming.mallchat.common.user.pojo.UserBackpack;
import com.ming.mallchat.common.user.service.UserBackpackService;
import com.ming.mallchat.common.user.mapper.UserBackpackMapper;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author 86150
 * @description 针对表【user_backpack(用户背包表)】的数据库操作Service实现
 * @createDate 2023-09-28 16:12:18
 */
@Service
public class UserBackpackServiceImpl implements UserBackpackService {

    @Autowired
    private UserBackPackDao userBackPackDao;

    @Autowired
    @Lazy
    private UserBackpackServiceImpl UserBackpackServiceImpl;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * @param uid            用户id
     * @param itemId         物品id
     * @param idempotentEnum 幂等类型
     * @param businessId     幂等id
     */
    @Override
    public void acquireItem(Long uid, Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        String idempotent = getIdempotent(itemId, idempotentEnum, businessId);
        UserBackpackServiceImpl.doAcquireItem(uid,itemId,idempotent);
    }

    @RedissonLock(key = "#idempotent",waitTime = 5000)
    public void doAcquireItem(Long uid, Long itemId, String idempotent) {
        UserBackpack userBackpack = userBackPackDao.getIdempotent(idempotent);
        if (Objects.nonNull(userBackpack)) {
            return;
        }
        userBackpack = UserBackpack.builder()
                .itemId(itemId)
                .uid(uid)
                .idempotent(idempotent)
                .status(YesOrNoEnum.NO.getStatus())
                .build();
        userBackPackDao.save(userBackpack);
        //用户收到物品的事件
        applicationEventPublisher.publishEvent(new ItemReceiveEvent(this, userBackpack));
    }

    private String getIdempotent(Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        return String.format("%d_%d_%s", itemId, idempotentEnum.getType(), businessId);
    }

}




